package core

import (
	"context"
	util2 "gitee.com/binny_w/go-util/v2"
	"go.uber.org/zap"
	"strings"
)

var MysqlClient *util2.MysqlClient
var MysqlVersion string

func mysqlInit() {
	dsn := make([]string, 0)
	dsn = append(dsn, Config.GetString("mysql.master"))
	slaves := Config.GetStrSlice("mysql.slaves")
	dsn = append(dsn, slaves...)

	var err error
	MysqlClient, err = util2.NewMysqlClientEasy(dsn...)
	if err != nil {
		Logger.Panic("mysql master connection panic", zap.Error(err), zap.Strings("dsn", dsn))
	}
	MysqlVersion, _ = MysqlClient.Version(context.Background())

	MysqlClient.Listener = func(ctx context.Context, query string, err error, params ...any) {
		var userName, actorName any
		if val := ctx.Value("user"); val != nil {
			if user, ok := val.(*util2.MysqlRow); ok && user != nil {
				userName = user.Get("name")
				actorName = user.Get("actorName")
			}
		}
		if err != nil {
			Logger.Error(
				"mysql query fail",
				zap.Error(err),
				zap.Any("actor", actorName),
				zap.Any("user", userName),
				zap.String("query", query),
				zap.Any("param", params),
			)
		} else if !strings.HasPrefix(strings.ToLower(query), "select") {
			Logger.Info(
				"mysql changing",
				zap.Any("actor", actorName),
				zap.Any("user", userName),
				zap.String("query", query),
				zap.Any("param", params),
			)
		}
		Logger.Debug(
			"mysql query debug",
			zap.Error(err),
			zap.Any("actor", actorName),
			zap.Any("user", userName),
			zap.String("query", query),
			zap.Any("param", params),
		)
	}
}
